/*
    Copyright (C) 2013 maik.jablonski@jease.org

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sample.web.task;

import jfix.db4o.Database;
import jfix.util.Arrays;
import jfix.util.Natural;
import jfix.zk.Label;
import jfix.zk.ObjectEditor;
import jfix.zk.Picklist;
import jfix.zk.Selectfield;
import jfix.zk.Textarea;
import jfix.zk.Textfield;
import sample.domain.Person;
import sample.domain.Project;
import sample.domain.Task;
import sample.service.Ids;
import sample.web.task.status.Statusfield;

public class Editor extends ObjectEditor<Task> {

	Label id = new Label();
	Selectfield project = new Selectfield();
	Textfield title = new Textfield();
	Textarea description = new Textarea();
	Picklist members = new Picklist(Natural.newComparator(), true);
	Statusfield status = new Statusfield();

	public void init() {
		add("Id", id);
		add("Project", project, "Please select the project for the task.");
		add("Title", title, "Please enter a title for the task.");
		add("Description", description, "Please enter a description for the task.");
		add("Members", members, "Please select the member which will work on the task.");
		add("Status", status, "Please set the status of the task.");
	}

	public void load() {
		id.setText(getObject().getId());
		project.setSelection(Natural.sort(Database.query(Project.class)),
				getObject().getProject());
		title.setText(getObject().getTitle());
		description.setText(getObject().getDescription());
		members.setSelection(Database.query(Person.class), getObject()
				.getMembers());
		status.setValue(getObject().getStatus());
	}

	public void save() {
		if (getObject().getId() == 0) {
			getObject().setId(Ids.next());
		}
		getObject().setProject((Project) project.getSelectedValue());
		getObject().setTitle(title.getText());
		getObject().setDescription(description.getText());
		getObject()
				.setMembers(Arrays.cast(members.getSelected(), Person.class));
		getObject().setStatus(status.getValue());
		Database.save(getObject());
	}

	public void delete() {
		Database.delete(getObject());
	}

	public void validate() {
		validate(project.isEmpty(), "Project is required");
		validate(title.isEmpty(), "Title is required");
	}

}
